package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * 登录方法
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //判断参数是否为null
        if (loginDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取参数中的电话和密码
        String password = loginDto.getPassword();
        String phone = loginDto.getPhone();
        //判断电话和密码是否为空  为空代表是游客
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(phone)){
            String token = AppJwtUtil.getToken(0L);
            //构建返回对象
            Map<String,Object> map = new HashMap<>();
            map.put("user",null);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
        //如果电话密码不为空，那么就是正常用户登录
        //根据phone查询用户对象
        LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApUser::getPhone,phone);
        ApUser apUser = apUserMapper.selectOne(queryWrapper);
        //判断返回的对象存不存在
        if (apUser == null){
            //返回用户数据不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //获取返回对象的密码和盐
        String salt = apUser.getSalt();
        String passwordFromDb = apUser.getPassword();

        String passwordAfterMd5 = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!passwordAfterMd5.equals(passwordFromDb)){
            //登录失败 构建失败对象，返回密码错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //屏蔽敏感数据
        apUser.setSalt("");
        apUser.setPassword("");
        //生成登录成功token
        String token = AppJwtUtil.getToken(apUser.getId().longValue());
        //构建结果集
        Map<String,Object> map = new HashMap<>(2);
        map.put("user",apUser);
        map.put("token",token);
        //返回数据
        return ResponseResult.okResult(map);
    }
}